<?php
/**
 * Log.php
 * Notes:
 * author: chen
 * DateTime: 2022/12/14 19:49
 * @package Xtsb\Cims\Log
 */

namespace Xtsb\Cims\Log;

class Log
{
  public static function info()
  {
    $request = app('request');
    $requestInfo = [
      'ip' => $request->ip(),
      'method' => $request->method(),
      'host' => $request->scheme . '://' . $request->host(),
      'uri' => $request->url(),
    ];

    if ($request->userInfo) {
      if (isset($request->userInfo->cuid)) {
        //企业登入
        $userInfo['cuid'] = $request->userInfo->cuid;
        $userInfo['cuaccount'] = $request->userInfo->cuaccount;
        $userInfo['title'] = $request->userInfo->title;
        $userInfo['name'] = $request->userInfo->name;
        $userInfo['label'] = $request->userInfo->label;
        $userInfo['uuid'] = $request->userInfo->uuid;
        $userInfo['uid'] = $request->userInfo->uid;
        $userInfo['sid'] = $request->userInfo->sid;
        $userInfo['dm_id'] = $request->userInfo->dm_id;
        $userInfo['dmp_id'] = $request->userInfo->dmp_id;
        $userInfo['username'] = $request->userInfo->username;
        $userInfo['login_time'] = $request->userInfo->login_time;
      } else {
        //施工人员登入
//        $userInfo['team_id'] = $request->userInfo->team_id;
//        $userInfo['team_name'] = $request->userInfo->team_name;
        $userInfo['worker_id'] = $request->userInfo->worker_id;
        $userInfo['name'] = $request->userInfo->name;
        $userInfo['id_no'] = $request->userInfo->id_no;
      }

    } else {
      $userInfo = [];
    }


    $logInfo = [
      "{$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}",
      '[ ROUTE ] ' . var_export(self::getRouteInfo(), true),
      '[ HEADER ] ' . var_export($request->header(), true),
      '[ USER ] ' . var_export($userInfo, true),
      '[ PARAM ] ' . var_export($request->param(), true),
      '---------------------------------------------------------------',
    ];
    $logInfo = implode(PHP_EOL, $logInfo) . PHP_EOL;
//    \think\facade\Log::record($logInfo, 'info');
    \think\facade\Log::channel('file')->info($logInfo);
    unset($userInfo);
  }

  /**
   * 获取路由信息
   * @return array
   */
  private static function getRouteInfo(): array
  {
    $request = app('request');
    return [
      'rule' => $request->rule()->getRule(),
      'route' => $request->rule()->getRoute(),
      'option' => $request->rule()->getOption(),
      'var' => $request->rule()->getVars(),
    ];
  }
}
